﻿/* 
 * Since 2008 - 2012
 */
package com.hh.bss.oa.controller;

import static com.hh.bss.util.extjs.JsonHelper.outJson;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.hh.bss.auth.client.OnlineUser;
import com.hh.bss.auth.entity.SystemUser;
import com.hh.bss.auth.service.SystemUserService;
import com.hh.bss.base.*;
import com.hh.bss.common.ConstantDic;
import com.hh.bss.common.page.*;
import com.hh.bss.common.page.impl.*;
import com.hh.bss.config.Environment;
import com.hh.bss.customer.entity.Customer;
import com.hh.bss.mail.SendMailInfo;
import com.hh.bss.mail.SendMailUtil;
import com.hh.bss.oa.dao.*;
import com.hh.bss.oa.entity.*;
import com.hh.bss.oa.service.*;
import com.hh.bss.oa.vo.query.*;
import com.hh.bss.project.entity.AccountPn;
import com.hh.bss.project.entity.AccountPnAttachment;
import com.hh.bss.project.entity.ContractJobCvInterview;
import com.hh.bss.project.entity.ContractJobCvJd;
import com.hh.bss.project.entity.ContractJobCvOffer;
import com.hh.bss.project.entity.ContractJobCvRecom;
import com.hh.bss.project.entity.SearchProjectCv;
import com.hh.bss.project.entity.SearchProjectInterview;
import com.hh.bss.project.service.AccountPnAttachmentService;
import com.hh.bss.project.service.ContractJobCvJdService;
import com.hh.bss.project.service.ContractJobCvRecomService;
import com.hh.bss.project.service.SearchProjectCvService;
import com.hh.bss.util.*;
import com.hh.bss.util.extjs.ExtJsPageHelper;
import com.hh.bss.util.extjs.ListRange;

import java.util.*;




@Controller
public class OaEmailSendController extends BaseSpringController {
	// 默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null;

	private OaEmailSendService oaEmailSendService;
	private SystemUserService systemUserService;
	private ContractJobCvRecomService contractJobCvRecomService;
	private SearchProjectCvService searchProjectCvService;
	private ContractJobCvJdService contractJobCvJdService;
	private OaEmailSend oaEmailSend;
	private AccountPnAttachmentService pnAttachmentService;

	java.lang.Integer id = null;
	private String[] items;

	public void setSystemUserServiceImpl(SystemUserService service) {
		this.systemUserService = service;
	}

	public void setContractJobCvRecomServiceImpl(ContractJobCvRecomService service) {
		this.contractJobCvRecomService = service;
	}

	public void setSearchProjectCvServiceImpl(SearchProjectCvService service) {
		this.searchProjectCvService = service;
	}

	public void setContractJobCvJdServiceImpl(ContractJobCvJdService service) {
		this.contractJobCvJdService = service;
	}

	/** 通过spring自动注入 */
	public void setOaEmailSendServiceImpl(OaEmailSendService service) {
		this.oaEmailSendService = service;
	}

	/** 通过spring自动注入 */
	public void setAccountPnAttachmentServiceImpl(AccountPnAttachmentService service) {
		this.pnAttachmentService = service;
	}

	public void setId(java.lang.Integer val) {
		this.id = val;
	}

	public String emailSendInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
			
		return "forward:/jsp/oa/oaEmailSend/emailSend.jsp";
			
    }
	public String crEmailSendInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		return "forward:/jsp/oa/oaEmailSend/crEmailSend.jsp";
		
    }
   public String jdEmailSendInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		return "forward:/jsp/oa/oaEmailSend/jdEmailSend.jsp";
		
    }
   public String rtEmailSendInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		return "forward:/jsp/oa/oaEmailSend/rtEmailSend.jsp";
		
   }
	public void setItems(String[] items) {
		this.items = items;
	}

	/**
	 * ExtGrid使用 列表
	 * 
	 * @throws IOException
	 */
	public void list(HttpServletRequest request, HttpServletResponse response, OaEmailSendQuery oaEmailSendQuery) throws IOException {
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, DEFAULT_SORT_COLUMNS);
		Page page = oaEmailSendService.findPage(oaEmailSendQuery);

		List<OaEmailSend> OaEmailSendlist = (List) page.getResult();
		ListRange<OaEmailSend> resultList = new ListRange<OaEmailSend>();
		resultList.setRows(OaEmailSendlist);
		resultList.setTotal(page.getTotalCount());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		outJson(response, resultList);
	}

	// 准备发送人选推荐邮件
	public void getcrsendemail(HttpServletRequest request, HttpServletResponse response, ContractJobCvRecom contractJobCvRecom) throws IOException {

		Map<String, Object> result = new HashMap<String, Object>();
		try {
			OnlineUser onlineUser = this.getOnlineManager(request, response).getOnlineUser();
			OaEmailSend oaEmailSend = oaEmailSendService.getCREmail(contractJobCvRecom, onlineUser);

			if (oaEmailSend != null)
				result.put("data", oaEmailSend);
			result.put("success", true);
			result.put("msg", "成功!");

		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);

	}

	// 发送职位jd邮件
	public void getjdsendemail(HttpServletRequest request, HttpServletResponse response) throws IOException {

		Map<String, Object> result = new HashMap<String, Object>();
		try {
			String cvId = request.getParameter("cvId");
			String jobId = request.getParameter("jobId");
			OnlineUser onlineUser = this.getOnlineManager(request, response).getOnlineUser();
			OaEmailSend oaEmailSend = oaEmailSendService.getJDEmail(StringHelper.parseInteger(cvId, 0), StringHelper.parseInteger(jobId, 0), onlineUser);

			if (oaEmailSend != null)
				result.put("data", oaEmailSend);
			result.put("success", true);
			result.put("msg", "成功!");

		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);

	}

	// 发送公司介绍邮件
	public void getcisendemail(HttpServletRequest request, HttpServletResponse response, Customer customer) throws IOException {

		Map<String, Object> result = new HashMap<String, Object>();
		try {

			OnlineUser onlineUser = this.getOnlineManager(request, response).getOnlineUser();
			OaEmailSend oaEmailSend = oaEmailSendService.getCIEmail(customer, onlineUser);

			if (oaEmailSend != null)
				result.put("data", oaEmailSend);
			result.put("success", true);
			result.put("msg", "成功!");

		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);

	}

	// 候选人答谢邮件
	public void getrtsendemail(HttpServletRequest request, HttpServletResponse response, ContractJobCvRecom contractJobCvRecom) throws IOException {

		Map<String, Object> result = new HashMap<String, Object>();
		try {
			OnlineUser onlineUser = this.getOnlineManager(request, response).getOnlineUser();
			OaEmailSend oaEmailSend = oaEmailSendService.getRTEmail(contractJobCvRecom, onlineUser);

			if (oaEmailSend != null)
				result.put("data", oaEmailSend);
			result.put("success", true);
			result.put("msg", "成功!");

		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);

	}

	// 发送保证期跟踪
	public void getogsendemail(HttpServletRequest request, HttpServletResponse response, ContractJobCvOffer contractJobCvOffer) throws IOException {

		Map<String, Object> result = new HashMap<String, Object>();
		try {
			OnlineUser onlineUser = this.getOnlineManager(request, response).getOnlineUser();
			OaEmailSend oaEmailSend = oaEmailSendService.getOGEmail(contractJobCvOffer, onlineUser);

			if (oaEmailSend != null)
				result.put("data", oaEmailSend);
			result.put("success", true);
			result.put("msg", "成功!");

		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);

	}

	// 客户面试
	public void getkivsendemail(HttpServletRequest request, HttpServletResponse response, ContractJobCvInterview contractJobCvInterview) throws IOException {

		Map<String, Object> result = new HashMap<String, Object>();
		try {
			OnlineUser onlineUser = this.getOnlineManager(request, response).getOnlineUser();
			OaEmailSend oaEmailSend = oaEmailSendService.getCustomerIVEmail(contractJobCvInterview, onlineUser);

			if (oaEmailSend != null)
				result.put("data", oaEmailSend);
			result.put("success", true);
			result.put("msg", "成功!");

		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);

	}

	// 顾问面试
	public void getgivsendemail(HttpServletRequest request, HttpServletResponse response, SearchProjectInterview searchProjectInterview) throws IOException {

		Map<String, Object> result = new HashMap<String, Object>();
		try {
			OnlineUser onlineUser = this.getOnlineManager(request, response).getOnlineUser();
			OaEmailSend oaEmailSend = oaEmailSendService.getConsultantIVEmail(searchProjectInterview, onlineUser);

			if (oaEmailSend != null)
				result.put("data", oaEmailSend);
			result.put("success", true);
			result.put("msg", "成功!");

		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);

	}

	// PN面试
	public void getpnsendemail(HttpServletRequest request, HttpServletResponse response, AccountPn accountPn) throws IOException {

		Map<String, Object> result = new HashMap<String, Object>();
		try {
			OnlineUser onlineUser = this.getOnlineManager(request, response).getOnlineUser();
			OaEmailSend oaEmailSend = oaEmailSendService.getPNEmail(accountPn, onlineUser);

			if (oaEmailSend != null)
				result.put("data", oaEmailSend);
			result.put("success", true);
			result.put("msg", "成功!");

		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);

	}

	/**
	 * extGrid保存
	 * 
	 * @throws IOException
	 */
	public void save(HttpServletRequest request, HttpServletResponse response, OaEmailSend oaEmailSend) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			// 设置创建用户和创建时间
			com.hh.bss.auth.client.OnlineManager onlineManager = super.getOnlineManager(request, response);
			com.hh.bss.auth.client.OnlineUser onlineUser = null;
			if (onlineManager != null) {
				onlineUser = onlineManager.getOnlineUser();
				if (onlineUser != null && com.hh.bss.util.BeanUtils.isExistsProperty(OaEmailSend.class, "creator")) {
					try {
						com.hh.bss.util.BeanUtils.setProperty(oaEmailSend, "creator", onlineUser.getUsername());
					} catch (Exception ex) {
					}
				}
			}

			if (com.hh.bss.util.BeanUtils.isExistsProperty(OaEmailSend.class, "createDt")) {
				try {
					com.hh.bss.util.BeanUtils.setProperty(oaEmailSend, "createDt", new Date());
				} catch (Exception ex) {
				}
			}

			// CR
			if (ConstantDic.EmailSourceType_CR.equals(oaEmailSend.getCallFrom())) {
				// 如果是发推荐信 验证 同一个职位 只能同一个人推荐
				if (oaEmailSendService.checkJobRecomSender(oaEmailSend)) {
					result.put("failure", true);
					result.put("msg", "人选已向该职位推荐过,不能重复推荐.");
					outJson(response, result);
					return;
				}

			}

			// 读取用户邮箱和密码
			// OnlineUser onlineUser=this.getOnlineManager(request,
			// response).getOnlineUser();
			SystemUser systemUser = null;
			if (onlineUser != null) {
				systemUser = systemUserService.findByUsername(onlineUser.getUsername());

			}
			SendMailInfo sendMailInfo = new SendMailInfo();

			sendMailInfo.setMailServerAddress(Environment.MAIL_SERVER);
			sendMailInfo.setAuth(true);

			if (systemUser != null && !StringHelper.isEmpty(systemUser.getEmail()) && !StringHelper.isEmpty(systemUser.getEmailPasswd())) {
				sendMailInfo.setUser(systemUser.getEmail());
				// 解密
				String mwpasswod = null;
				try {
					mwpasswod = new String(DESHelper.desDecode(DESHelper.hex2byte(systemUser.getEmailPasswd()), Environment.SECURE_KEY));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				sendMailInfo.setPassword(mwpasswod);
				// sendMailInfo.setPassword(systemUser.getEmailPasswd());
			} else {
				// 没有设置用户邮箱和密码则使用默认的
				sendMailInfo.setUser(Environment.MAIL_DEFAULT_SENDER);
				sendMailInfo.setPassword(Environment.MAIL_DEFAULT_SENDER_PASSWORD);
			}
			System.out.println("MailServerAddress:"+sendMailInfo.getMailServerAddress()+"-User:"+sendMailInfo.getUser()+"-password:"+sendMailInfo.getPassword());
			sendMailInfo.setTitle(oaEmailSend.getSubject());
			sendMailInfo.setContent(oaEmailSend.getContent());
			sendMailInfo.setSenderAddress(oaEmailSend.getSender());
			sendMailInfo.setToAddress(oaEmailSend.getReciever());
			sendMailInfo.setCcAddress(oaEmailSend.getCcreciever());
			sendMailInfo.setBCcAddress(oaEmailSend.getBccreciever());
			sendMailInfo.setReplysign(oaEmailSend.isReplysign());

			oaEmailSend.setSendDt(new Date()); // 设置发送时间

			// 如果有上传的附件，则保存，优先使用上传的附件
			MultipartHttpServletRequest multipartRequest = null;
			MultipartFile multipartFile = null;
			MultipartFile multipartFileEn = null;
			try {
				multipartRequest = (MultipartHttpServletRequest) request;
				multipartFile = multipartRequest.getFile("uploadFile"); // 中文
				multipartFileEn = multipartRequest.getFile("uploadFileEn"); // 英文
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			if (multipartRequest != null && multipartFile != null && !multipartFile.isEmpty()) {
				oaEmailSendService.saveFile(multipartRequest, multipartFile, oaEmailSend, 1);
			}

			if (multipartRequest != null && multipartFileEn != null && !multipartFileEn.isEmpty()) {
				oaEmailSendService.saveFile(multipartRequest, multipartFileEn, oaEmailSend, 2);
			}
			if (!StringHelper.isEmpty(oaEmailSend.getAttachment())) { // 如果存在附件
																		// 1
				String fileRealPath = request.getSession().getServletContext().getRealPath(oaEmailSend.getAttachment());
				File f = new File(fileRealPath);
				if (f.exists()) {
					//String preName = multipartFile.getOriginalFilename();
					String preName = oaEmailSend.getAttachment();
					if (!StringHelper.isEmpty(oaEmailSend.getAttachmentName()))
						if (!ConstantDic.EmailSourceType_PN.equals(oaEmailSend.getCallFrom())) {
							sendMailInfo.getAttachmentFiles().put(oaEmailSend.getAttachmentName(), fileRealPath);
						} else {
							// String preName =
							// multipartFile.getOriginalFilename().substring(0,multipartFile.getOriginalFilename().indexOf("."));
							sendMailInfo.getAttachmentFiles().put(preName, fileRealPath);
						}
					else
						sendMailInfo.getAttachmentFiles().put(preName, fileRealPath);
				}
			}
			if (!StringHelper.isEmpty(oaEmailSend.getAttachment2())) { // 如果存在附件
																		// 2
				String fileRealPath = request.getSession().getServletContext().getRealPath(oaEmailSend.getAttachment2());
				File f = new File(fileRealPath);
				if (f.exists()) {
					//String preName = multipartFileEn.getOriginalFilename();
					String preName = oaEmailSend.getAttachment();
					if (!StringHelper.isEmpty(oaEmailSend.getAttachment2Name()))
						sendMailInfo.getAttachmentFiles().put(oaEmailSend.getAttachment2Name(), fileRealPath);
					else
						sendMailInfo.getAttachmentFiles().put(preName, fileRealPath);
				}
			}
			// 验证

			oaEmailSendService.save(oaEmailSend);

			// 保存发送记录

			// 更新状态

			if (SendMailUtil.sendNoticeMail(sendMailInfo)) {
				result.put("success", true);
				if (ConstantDic.EmailSourceType_JD.equals(oaEmailSend.getCallFrom()) || ConstantDic.EmailSourceType_CR.equals(oaEmailSend.getCallFrom()))
					saveJD(oaEmailSend, onlineUser);
				// 如果是发推荐信 则更更新 推荐记录表示 isEmail 字段
				if (ConstantDic.EmailSourceType_CR.equals(oaEmailSend.getCallFrom())) {
					ContractJobCvRecom jobCvRecom = (ContractJobCvRecom) contractJobCvRecomService.getById(oaEmailSend.getCallId());
					if (jobCvRecom != null) {
						if (!"1".equals(jobCvRecom.getIsEmail())) {
							jobCvRecom.setIsEmail(1); // 更新为已发推荐信
							jobCvRecom.setRecomDt(new Date());
							if (StringUtils.isNotEmpty(oaEmailSend.getAttachment())) {
								jobCvRecom.setUploadDoc(oaEmailSend.getAttachment());
							}
							if (StringUtils.isNotEmpty(oaEmailSend.getAttachment2())) {
								jobCvRecom.setUploadDocEn(oaEmailSend.getAttachment2());
							}
							// jobCvRecom.setUploadDoc(oaEmailSend.getAttachment()
							// == null ? );
							contractJobCvRecomService.update(jobCvRecom);
						}
					}
				}

				if (ConstantDic.EmailSourceType_PN.equals(oaEmailSend.getCallFrom())) {
					String pnId = request.getParameter("pnId");
					if (StringUtils.isNotEmpty(pnId)) {
						String preName = multipartFile.getOriginalFilename().substring(0, multipartFile.getOriginalFilename().indexOf("."));
						AccountPnAttachment attachment = new AccountPnAttachment();
						attachment.setPnId(Integer.parseInt(pnId));
						attachment.setName(preName);
						attachment.setFileName(oaEmailSend.getAttachment());
						attachment.setCreator(onlineManager.getOnlineUser().getUsername());
						attachment.setCreateDt(new Date());
						pnAttachmentService.save(attachment);
					}

				}

				result.put("msg", "发送成功!");
			} else {
				result.put("failure", true);
				result.put("msg", "发送失败!");
			}
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	// 处理 jd和人选推荐邮件
	private void saveJD(OaEmailSend oaEmailSend, OnlineUser onlineUser) {
		ContractJobCvJd contractJobCvJd = new ContractJobCvJd();
		contractJobCvJd.setCreateDt(new Date());
		contractJobCvJd.setJobId(StringHelper.parseInteger(oaEmailSend.getJobId(), 0));
		contractJobCvJd.setReciever(oaEmailSend.getRecieverName());
		contractJobCvJd.setSubject(oaEmailSend.getSubject());
		contractJobCvJd.setContent(oaEmailSend.getContent());
		contractJobCvJd.setAttachment(oaEmailSend.getAttachment());
		contractJobCvJd.setAttachment2(oaEmailSend.getAttachment2());
		contractJobCvJd.setSenderEmail(oaEmailSend.getSender());
		contractJobCvJd.setRecieveEmail(oaEmailSend.getReciever());
		contractJobCvJd.setCvId(StringHelper.parseInteger(oaEmailSend.getCvId(), 0));

		if (ConstantDic.EmailSourceType_JD.equals(oaEmailSend.getCallFrom()))
			contractJobCvJd.setType(ContractJobCvJd.TYPE_JD);
		if (ConstantDic.EmailSourceType_CR.equals(oaEmailSend.getCallFrom()))
			contractJobCvJd.setType(ContractJobCvJd.TYPE_JR);

		if (onlineUser != null)
			contractJobCvJd.setCreator(onlineUser.getUsername());
		contractJobCvJdService.save(contractJobCvJd);
		if (ConstantDic.EmailSourceType_JD.equals(oaEmailSend.getCallFrom())) {
			ContractJobCvRecom contractJobCvRecom = contractJobCvRecomService.getContractJobCvRecom(StringHelper.parseInteger(oaEmailSend.getJobId(), 0), StringHelper.parseInteger(oaEmailSend.getCvId(), 0));

			if (contractJobCvRecom != null) {
				contractJobCvRecom.setStatus(SearchProjectCv.STATUS_JD);
				contractJobCvRecomService.updateRecomStatus(contractJobCvRecom);
			} else {
				searchProjectCvService.updateProjectCvStatus(StringHelper.parseInteger(oaEmailSend.getJobId(), 0), StringHelper.parseInteger(oaEmailSend.getCvId(), 0), SearchProjectCv.STATUS_JD);
			}
		}

	}

	/**
	 * extGrid修改
	 * 
	 * @throws IOException
	 */
	public void update(HttpServletRequest request, HttpServletResponse response, OaEmailSend oaEmailSend) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			OaEmailSend oldoaEmailSend = (OaEmailSend) oaEmailSendService.getById(oaEmailSend.getId());

			bind(request, oldoaEmailSend);
			// 设置修改用户和修改时间
			com.hh.bss.auth.client.OnlineManager onlineManager = super.getOnlineManager(request, response);
			if (onlineManager != null) {
				com.hh.bss.auth.client.OnlineUser onlineUser = onlineManager.getOnlineUser();
				if (onlineUser != null && com.hh.bss.util.BeanUtils.isExistsProperty(OaEmailSend.class, "modifier")) {
					try {
						com.hh.bss.util.BeanUtils.setProperty(oldoaEmailSend, "modifier", onlineUser.getUsername());
					} catch (Exception ex) {
					}
				}
			}

			if (com.hh.bss.util.BeanUtils.isExistsProperty(OaEmailSend.class, "modifiedDt")) {
				try {
					com.hh.bss.util.BeanUtils.setProperty(oldoaEmailSend, "modifiedDt", new Date());
				} catch (Exception ex) {
				}
			}

			oaEmailSendService.update(oldoaEmailSend);
			result.put("success", true);
			result.put("msg", "修改成功!");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	/**
	 * extGrid删除
	 * 
	 * @throws IOException
	 */
	public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String ids = request.getParameter("ids");
		String[] idarray = ids.split(",");
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			for (int i = 0; i < idarray.length; i++) {
				java.lang.Integer id = new java.lang.Integer((String) idarray[i]);
				oaEmailSendService.removeById(id);
			}
			result.put("success", true);
			result.put("msg", "删除成功");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

}
